/*
    Allows to perform CRUD operations on SharePoint List
*/

var ListUtility = {

    GetListItems: function (requestUri) {
        var listItems = null;
        var listItemsCall = $.ajax({
            url: requestUri,
            async: false,
            type: "GET",
            dataType: "json",
            headers: {
                Accept: "application/json;odata=verbose"
            }
        });
        listItemsCall.done(function (data, textStatus, jqXHR) {
            listItems = data.d.results;
        });
        listItemsCall.fail(function (error, textStatus, errorText) {
            alert("Error occurred in retrieving data: " + errorText);
            console.log(JSON.stringify(error));
        });
        return listItems;
    },

    GetSingleListItem: function (requestUri) {      
        var itemdata = null;
        var listItemCall = $.ajax({
            url: requestUri,
            async: false,
            type: "GET",
            dataType: "json",
            headers: {
                Accept: "application/json;odata=verbose"
            }
        });
        listItemCall.done(function (data, textStatus, jqXHR) {
            if (data.d.results.length > 0) {
                itemdata = data.d.results[0];
            }
            else {
                alert("Item not found!");
            }
        });
        listItemCall.fail(function (error, textStatus, errorText) {
            alert("Error occurred in retrieving data: " + errorText);
            console.log(JSON.stringify(error));
        });
        return itemdata;
    },

    GetItemTypeForListName: function (name) {
        return "SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
    },

    AddListItem: function (listname, metadata) {
        var success = false;
        var item = $.extend({
            "__metadata": {
                "type": ListUtility.GetItemTypeForListName(listname)
            }
        }, metadata);

        alert(JSON.stringify(item))
        // Executing our add
        var addItemCall = $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items",
            type: "POST",
            async: false,
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            }
        });
        addItemCall.done(function (data, textStatus, jqXHR) {
            success = true;
        });
        addItemCall.fail(function (error, textStatus, errorText) {
            console.log(JSON.stringify(error));
            success = false;
        });
        return success;
    },

    UpdateListItem: function (listname, requestUri, metadata) {
        var success = false;
        var itemData = ListUtility.GetSingleListItem(requestUri);
        if (itemData != null) {
            var item = $.extend({
                "__metadata": {
                    "type": ListUtility.GetItemTypeForListName(listname)
                }
            }, metadata);
            updateItemCall = $.ajax({
                url: itemData.__metadata.uri,
                type: "POST",
                async: false,
                contentType: "application/json;odata=verbose",
                data: JSON.stringify(item),
                headers: {
                    "Accept": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "X-HTTP-Method": "MERGE",
                    "If-Match": itemData.__metadata.etag
                }
            });
            updateItemCall.done(function (data, textStatus, jqXHR) {
                success = true;
            });
            updateItemCall.fail(function (error, textStatus, errorText) {
                console.log(JSON.stringify(error));
                success = false;
            });
        }
        return success;
    },

    DeleteListItem: function (requestUri) {
        var success = false;
        var itemData = ListUtility.GetSingleListItem(requestUri);
        if (itemData != null) {
            var deleteItemCall = $.ajax({
                url: itemData.__metadata.uri,
                type: "POST",
                async: false,
                headers: {
                    "Accept": "application/json;odata=verbose",
                    "X-Http-Method": "DELETE",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "If-Match": itemData.__metadata.etag
                }
            });
            deleteItemCall.done(function (data, textStatus, jqXHR) {
                success = true;
            });
            deleteItemCall.fail(function (error, textStatus, errorText) {
                console.log(JSON.stringify(error));
                success = false;
            });
        }
        return success;
    },

};